import { computed, reactive } from 'vue'
import {
  clearAuthSession,
  getAuthToken,
  loadStoredUser,
  login as loginRequest,
  saveAuthSession,
} from '../api/client'

const state = reactive({
  user: loadStoredUser(),
  token: getAuthToken(),
  loading: false,
  error: '',
})

const isAuthenticated = computed(() => Boolean(state.user))

async function login(credentials) {
  state.loading = true
  state.error = ''
  try {
    const response = await loginRequest(credentials)
    if (response?.token) {
      saveAuthSession({
        token: response.token,
        user: response.user,
      })
      state.user = response.user
      state.token = response.token
      state.error = ''
    }
    return response
  } catch (error) {
    state.error = error?.message || '登录失败，请稍后再试'
    throw error
  } finally {
    state.loading = false
  }
}

function logout() {
  clearAuthSession()
  state.user = null
  state.token = ''
  state.error = ''
}

export function useAuth() {
  return {
    state,
    user: computed(() => state.user),
    error: computed(() => state.error),
    loading: computed(() => state.loading),
    isAuthenticated,
    login,
    logout,
  }
}

